import fs from 'fs';
import { Canvas,FontLibrary } from 'skia-canvas';
import {width,height} from './config'
// 模拟抗锯齿
function testAntialias(ctx, width, height) {

// 获取像素数据
    const imgData = ctx.getImageData(0, 0, width, height);
    const data = imgData.data;
    // const threshold = 128;
    const threshold = 95;
// 二值化阈值
    for (let i = 0; i < data.length; i += 4) {
        // data[i] = R, data[i+1] = G, data[i+2] = B
        // data[i+3] = A
        const gray = 0.299 * data[i] + 0.587 * data[i+1] + 0.114 * data[i+2];
        if (gray < threshold) {
            data[i] = data[i+1] = data[i+2] = 0; // 黑
            data[i+3] = 255;
        } else {
            data[i] = data[i+1] = data[i+2] = 255; // 白
            data[i+3] = 255;
        }
    }

    ctx.putImageData(imgData, 0, 0);
}

export async function skiaCanvasTest() {
    console.time('skiaCanvasTest');
// 可选：加载自定义字体
// 注册字体（路径 + 字体名称）
    FontLibrary.use('ddjinbu', './font/ddjinbu.ttf');

    const canvas = new Canvas(width, height);
    const ctx = canvas.getContext('2d');

// 背景
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, width, height);

// 设置文字样式
    ctx.fillStyle = '#000';
    // ctx.font = '400 21px "微软雅黑"';
    ctx.font = '400 21px ddjinbu';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

// 渲染文字
    ctx.fillText('你好钉钉进步体!', width / 2, height / 2);
    ctx.imageSmoothingEnabled = true;
    // testAntialias(ctx,width,height)

// 导出 PNG
    const buffer = await canvas.toBuffer('image/png');
    fs.writeFileSync('./image/skia-canvas-test.png', buffer);
    console.log('生成 text.png 成功');
    console.timeEnd('skiaCanvasTest');
    return Promise.resolve('./image/skia-canvas-test.png');

}
